# 作者：我只是代码的搬运工
# coding:utf-8

# sayhello的视图函数
from flask import Blueprint, render_template, redirect, url_for, flash

from exts import db
from sayhello.forms import HelloForm
from sayhello.models import Message

say = Blueprint('sayhello', __name__)


@say.route('/', methods=['GET', 'POST'])
def index():
    # 创建一个表单对象
    form = HelloForm()
    # 验证表单
    if form.validate_on_submit():
        # 获取表单数据
        name = form.name.data
        body = form.body.data
        message = Message(body=body, name=name)
        db.session.add(message)
        db.session.commit()
        flash('你的留言已经成功提交啦!')
        return redirect(url_for('index'))
    # 从数据库查询留言
    messages = Message.query.order_by(Message.timestamp.desc()).all()
    return render_template('index.html', form=form, messages=messages)
